package socket;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class Server extends Thread{

    private ServerSocket serverSocket;
    //将输出流存入共享集合用于广播消息
    private List<PrintWriter> allOut = new ArrayList<>();

    public Server(){
        try {
            System.out.println("正在启动服务端");
            serverSocket = new ServerSocket(8088);
            System.out.println("服务端启动完毕!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void start(){
        try {
            while(true){
                System.out.println("等待客户端连接...");
                Socket socket = serverSocket.accept();
                System.out.println("一个客户端连接了");
                //启动一个线程交互客户端

                ClientHandler clientHandler = new ClientHandler(socket);
                Thread t = new Thread(clientHandler);
                t.start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



    public static void main(String[] args) {
        Server server = new Server();
            server.start();
    }

    /**
     * 该线程负责与指定的客户端进行交互
     * */
    private class ClientHandler implements Runnable{
        private Socket socket;
        private String host;//客户端地址信息
        public ClientHandler(Socket socket){
            this.socket = socket;
            //获取远端计算机地址
            host = socket.getInetAddress().getHostAddress();
        }

        @Override
        public void run() {
            PrintWriter pw = null;
            try {
                InputStream is = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr);

                //通过socket获取输出流用于将消息发给客户端
                OutputStream out = socket.getOutputStream();
                OutputStreamWriter osw = new OutputStreamWriter(out,StandardCharsets.UTF_8);
                BufferedWriter bw = new BufferedWriter(osw);
                pw = new PrintWriter(bw,true);

                //将输出流存入共享集合用于广播消息
                synchronized (allOut){
                    allOut.add(pw);
                }

                //广播消息通知所有客户端用户上线
                sendMessage(host+"上线了，当前在线人数："+allOut.size());

                String line;
                while((line = br.readLine()) != null){
                    sendMessage(host+":"+line);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                //客户端断开操作处理
                //移除客户端输出流从allOut删除
                synchronized (allOut){
                    allOut.remove(pw);
                }
                try {
                    //将socket关闭释放底层资源
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                //客户端下线
                sendMessage(host+"下线了，当前在线人数："+allOut.size());
            }
        }

        //将所有消息发送给客户端
        private void sendMessage(String message){
            System.out.println(message);
            //将消息发送给所有客户端
            synchronized (allOut){
                for (PrintWriter o : allOut){
                    o.println(message);
                }
            }
        }
    }
}